<template>
  <van-button
    class="follow-btn"
    type="info"
    color="#3296fa"
    round
    size="small"
    icon="plus"
    v-if="!isFollowed"
    @click="onFollowed"
    :loading="isFollowLoading"
  >关注</van-button>
  <van-button
    class="follow-btn"
    round
    size="small"
    v-else
    @click="onFollowed"
    :loading="isFollowLoading"
  >已关注</van-button>
</template>

<script>
import { addUserFollowed, deleteUserFollowed } from '@/api/user.js'
export default {
  data () {
    return {
      isFollowLoading: false
    }
  },

  props: {
    // 接收 articles.is_followed
    isFollowed: {
      type: Boolean,
      required: true
    },
    // 接收的 articles.aut_id
    autId: {
      type: [Number, Object],
      required: true
    }
  },

  // 自定义v-model的解析规则
  model: {
    // 属性的解析
    prop: 'isFollowed',
    // 事件的解析
    event: 'updateIsFollowed'
  },

  created () {

  },

  methods: {
    // 关于关注的事件
    async onFollowed () {
      this.isFollowLoading = true
      try {
        if (this.isFollowed) {
          // 当前关注 进行取关
          await deleteUserFollowed(this.autId)
          this.$toast('取关成功')
        } else {
          await addUserFollowed(this.autId)
          this.$toast('关注成功')
        }
        // 同步视图
        this.$emit('updateIsFollowed', !this.isFollowed)
      } catch (err) {
        console.log(err)
        // 判断错误类型为关注自己
        if (err.response && err.response.status === 400) {
          return this.$toast('亲,不能关注自己呦')
        }
        this.$toast('操作失败')
      }
      this.isFollowLoading = false
    }
  }
}
</script>

<style scoped lang='less'>

</style>
